package com.zzx.test.reflection;

import com.zzx.test.entity.Person;
import org.junit.Test;

import java.lang.reflect.Method;

/**
 * @ClassName: ReflectionTest2
 * @Description: 反射效率测试类
 * @Author zhouzhixin
 * @Date 2021/12/3
 * @Version 1.0
 */
public class ReflectionTest2 {

    @Test
    public void test1() {
        hi1();
        hi2();
        hi3();
    }

    public void hi1() {
        long start = System.currentTimeMillis();
        Person person = new Person();
        for (int i = 0; i < 9_0000_0000; i++) {
            person.hi();
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start + "ms");
    }

    public void hi2() {
        try {
            long start = System.currentTimeMillis();
            Class<?> aClass = Class.forName("com.zzx.test.entity.Person");
            Object obj = aClass.newInstance();
            Method hi = aClass.getMethod("hi");
            for (int i = 0; i < 9_0000_0000; i++) {
                hi.invoke(obj);
            }
            long end = System.currentTimeMillis();
            System.out.println(end - start + "ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void hi3() {
        try {
            long start = System.currentTimeMillis();
            Class<?> aClass = Class.forName("com.zzx.test.entity.Person");
            Object obj = aClass.newInstance();
            Method hi = aClass.getMethod("hi");
            hi.setAccessible(true);
            for (int i = 0; i < 9_0000_0000; i++) {
                hi.invoke(obj);
            }
            long end = System.currentTimeMillis();
            System.out.println(end - start + "ms");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
